package com.fourth_groups.shopping121store.ui.category.myfragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fourth_groups.shopping121store.Constants;
import com.fourth_groups.shopping121store.R;
import com.fourth_groups.shopping121store.bean.CategoryGroupLeftLvBean;
import com.fourth_groups.shopping121store.bean.CategoryGroupRightBean;
import com.fourth_groups.shopping121store.http.OkHttpClientUtils;
import com.fourth_groups.shopping121store.ui.category.activity.CategoryDetailActivity;
import com.fourth_groups.shopping121store.ui.category.adapter.commonadapter.CommonAdapter;
import com.fourth_groups.shopping121store.ui.category.adapter.commonadapter.ViewHolder;
import com.fourth_groups.shopping121store.utils.GsonImpl;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class AllRightFragment extends Fragment {
    private List<CategoryGroupRightBean.DataBean.ChildrenBean> childrenBeans = new ArrayList<>();
    private static final int SUCCESS = 1;
    private LinearLayout mLLRightContent;
    private LinearLayout.LayoutParams mLlGv = null;
    private LinearLayout.LayoutParams mLlTv = null;

    public AllRightFragment() {
        // Required empty public constructor
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SUCCESS:
                    childrenBeans = (List<CategoryGroupRightBean.DataBean.ChildrenBean>) msg.obj;
                    setData();
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_all_right, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Bundle bundle = getArguments();
        CategoryGroupLeftLvBean.DataBean.CategoryBean categoryBean = (CategoryGroupLeftLvBean.DataBean.CategoryBean) bundle.getSerializable("bean");
        String flag = bundle.getString("flag");
        int id = categoryBean.getId();
        String url = null;
        if (flag.equals("all")) {
            url = Constants.ALL_CATEGORY_GROUP_URL.replace("%d", Integer.toString(id));
        } else if (flag.equals("jd")) {
            url = Constants.JD_CATEGORY_GROUP_URL.replace("%d", Integer.toString(id));
        }
        loadData(view, url);
        mLLRightContent = (LinearLayout) view.findViewById(R.id.all_right_ll_content);

    }

    private void setData() {
        for (int i = 0; i < childrenBeans.size(); i++) {

            //固定单个Item的高度
            int heightUnit = (int) TypedValue
                    .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 128, getResources().getDisplayMetrics());
            //计算Gridview的总高度
            final int height;
            if (childrenBeans.get(i).getList().size() % 3 == 0) {
                height = (childrenBeans.get(i).getList().size() / 3) * heightUnit;
            } else {
                height = (childrenBeans.get(i).getList().size() / 3 + 1) * heightUnit;
            }

            mLlTv = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);

            mLlGv = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT
                    , (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP
                    , 30, getResources().getDisplayMetrics()));

            TextView tv_title = new TextView(getActivity());
            tv_title.setLayoutParams(mLlGv);
            tv_title.setText(childrenBeans.get(i).getName());
            tv_title.setPadding(10, 15, 0, 0);
            tv_title.setTextSize(14);
            mLLRightContent.addView(tv_title);

            GridView gridView = new GridView(getActivity());
            gridView.setNumColumns(3);
            gridView.setVerticalSpacing(30);
            gridView.setLayoutParams(mLlTv);
            gridView.setHorizontalSpacing(40);

            List<CategoryGroupRightBean.DataBean.ChildrenBean.ListBean> listBean = childrenBeans.get(i).getList();
            CommonAdapter<CategoryGroupRightBean.DataBean.ChildrenBean.ListBean> adapter =
                    new CommonAdapter<CategoryGroupRightBean.DataBean.ChildrenBean.ListBean>(getActivity(),
                            R.layout.list_item_category_right_gv) {
                        @Override
                        public void convert(ViewHolder helper, CategoryGroupRightBean.DataBean.ChildrenBean.ListBean item) {
                            helper.setText(R.id.tv_category_all_right_item, item.getName());
                            helper.setImageByUrl(getActivity(), R.id.iv_category_all_right_item, item.getImage());
                        }
                    };
            adapter.setData(listBean);
            gridView.setAdapter(adapter);
            mLLRightContent.addView(gridView);

            final int finalI = i;
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    CategoryGroupRightBean.DataBean.ChildrenBean.ListBean listBean = childrenBeans.get(finalI).getList().get(position);
                    Intent intent = new Intent(getActivity(), CategoryDetailActivity.class);
                    Bundle bundle = new Bundle();
                    String title = listBean.getName();
                    bundle.putString("title", title);
                    bundle.putSerializable("listBean", listBean);
                    intent.putExtra("bundle", bundle);
                    startActivity(intent);
                }
            });
        }
    }

    private void loadData(View view, String url) {
        OkHttpClientUtils.getDataAsync(view.getContext(), url, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Toast.makeText(getActivity(), "下载失败，请检查您的网络数据是否打开！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    String json = response.body().string();
                    CategoryGroupRightBean bean = GsonImpl.get().toObject(json, CategoryGroupRightBean.class);
                    List<CategoryGroupRightBean.DataBean.ChildrenBean> childrenBean = bean.getData().getChildren();
                    Message message = new Message();
                    message.what = SUCCESS;
                    message.obj = childrenBean;
                    mHandler.sendMessage(message);
                }
            }
        }, new Object());
    }


}